--- modbus-tcp 从站
module(...,package.seeall)

local THISDEV,uid = 0x01, 2
---仿真回复阵列，实际数字位则用业务状态/数据替换
REG_T={}
REG_T[0x01]={} 
REG_T[0x02]={} 
REG_T[0x03]={THISDEV,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} 
REG_T[0x04]={THISDEV,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} 
--[[
--   起始        地址    功能代码    数据       CRC校验    结束
-- 3.5 字符     8 位      8 位      N x 8 位   16 位      3.5 字符
--- 发送modbus数据函数
@function   modbus_resp
@param      addr : 从站地址
            func:功能码
            hexdat 回复的数据 HEX STRING
@return     无
@usage modbus_resp("0x01","0x01","0x0101","0x04")
]]
local function modbus_resp(index,addr,func,hexdat)
    local data = (string.format("%04x0000%04x",index,2+#hexdat)..string.format("%02x%02x",addr,func)..hexdat):fromHex()
    sys.publish("UART_SENT_RDY_"..uid , uid, data)
end
function modbus_read(order)
    if order and order:len()>10 then
        local nextpos,index,type,len,dev, func,reg,bytlen = pack.unpack(order,">HHHbbHH")
        log.info("nextpos ,dev, func ",nextpos,string.format("%02X,%02X", dev or 0, func or 0))
        order = order:sub(7,-1)--去掉头
        if dev == THISDEV then
            if func == 0x03 or func == 0x04 then
                local _, bytlen = pack.unpack(order, ">H", 5)
                bytlen = bytlen+reg-1
                if bytlen <= #REG_T[func] then
                    local strhex = ""
                    for i = reg, bytlen do
                        strhex = strhex .. string.format("%04x", REG_T[func][i] or 0)
                    end
                   -- log.info(" bytlen , #REG_T[func], msk,strhex", bytlen, #REG_T[func], msk, strhex)
                    modbus_resp(index,THISDEV, func, string.format("%02x%s", #strhex / 2, strhex))
                else
                    modbus_resp(index,THISDEV, func + 0x80, string.format("%02x", 0x02))
                end
            end
        end
    end
end